const crypto = require('crypto')
const config = require('../util/config')
const mongoMng = require('../mng/mongoMng')
const formatDate = require('../../lib/formatDate')
const logger = require('log4js').getLogger()
const fs = require('fs')
const getNormalDistribution = require('get-normal-distribution')

var is_running = false

var last_mch_billno = ''
while (last_mch_billno.length < 28)
    last_mch_billno += '0'

function getWechatBillno() {
    var mch_billno = Math.floor(new Date().getTime() / 1000) + ''
    var no = '1'
    if (mch_billno < last_mch_billno) {
        no = (parseInt(last_mch_billno.substring(mch_billno.length)) + 1) + ''
    }
    while (mch_billno.length + no.length < 28)
        mch_billno += '0'
    mch_billno += no
    last_mch_billno = mch_billno
    return mch_billno
}

function sendWechatRedPack(parm) {
    var kvs = []
    for (var k in parm)
        kvs.push(k + '=' + parm[k])
    stringA = kvs.join('&')

    stringSignTemp = stringA + '&key=etourlyetourlyetourlyetourly9876'

    parm.sign = crypto.createHash('md5').update(stringSignTemp).digest('hex').toUpperCase()

    var data = '<xml>'
    for (var k in parm)
        data += '<' + k + '>' + parm[k] + '</' + k + '>'
    data += '</xml>'
    logger.debug('[' + __filename + ':' + __line + ']', data)

    return new Promise((resolve, reject) => {
        require('../util/getHtml')({
            url: 'https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack',
            data,
            key: fs.readFileSync(__dirname + '/../apiclient_key.pem'),
            cert: fs.readFileSync(__dirname + '/../apiclient_cert.pem')
        }).then(result => {
            logger.debug('[' + __filename + ':' + __line + ']', result)
            if (result.indexOf('<result_code><![CDATA[SUCCESS]]></result_code>') != -1)
                resolve()
            else
                reject()
        }, result => {
            logger.error('[' + __filename + ':' + __line + ']', result)
            reject(result)
        })
    })
}

function randomString(len) {
    len = len || 32
    var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
    var maxPos = $chars.length
    var pwd = ''
    for (i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
    }
    return pwd
}

function findCustomerForAllBills() {
    return new Promise(resolve => {
        mongoMng.db.collection('bill').find({
            customer_phone: null
        }).toArray((err, result) => {
            if (err) {
                logger.error('[' + __filename + ':' + __line + ']', err)
                resolve()
                return
            }
            // logger.debug('[' + __filename + ':' + __line + ']', result)
            result.forEach(item => {
                exports.findCustomerForBill(item).then(result => {}, result => {
                    // if (result)
                    //     logger.error('[' + __filename + ':' + __line + ']', result)
                })
            })
            resolve()
        })
    })
}

function handleAllTaobaoBills() {
    return new Promise(resolve => {
        mongoMng.db.collection('bill').find({
            taobaoTradeParentId: {
                $ne: null
            },
            payStatus: 3,
            returnTime: null,
            customer_phone: {
                $ne: null
            }
        }).toArray((err, result) => {
            if (err) {
                logger.error('[' + __filename + ':' + __line + ']', err)
                resolve()
                return
            }
            var returnObjs = {}
            result.forEach(item => {
                var title = item.auctionTitle.replace(/\+/g, '').replace(/&/g, '').replace(/%/g, '')
                if (returnObjs[item.customer_phone]) {
                    if (returnObjs[item.customer_phone].amount < 1) {
                        returnObjs[item.customer_phone].amount += Math.round(parseFloat(item.feeString) * config.returnRate * 100) / 100
                        returnObjs[item.customer_phone].remark += ';' + title
                        returnObjs[item.customer_phone].items.push(item)
                    }
                } else {
                    returnObjs[item.customer_phone] = {
                        customer_phone: item.customer_phone,
                        amount: Math.round(parseFloat(item.feeString) * config.returnRate * 100) / 100,
                        remark: title,
                        items: [item]
                    }
                }
            })
            let promises = []
            for (var key in returnObjs) {
                if (returnObjs[key].amount >= 1) {
                    promises.push(doReturn(returnObjs[key]))
                }
            }
            Promise.all(promises).then(result => {
                resolve()
            })
        })
    })
}

function handleAllTaobaoBills2() {
    return new Promise(resolve => {
        mongoMng.db.collection('bill').find({
            tradeParentId: {
                $ne: null
            },
            tkStatus: 3,
            returnTime: null,
            customer_phone: {
                $ne: null
            }
        }).toArray((err, result) => {
            if (err) {
                logger.error('[' + __filename + ':' + __line + ']', err)
                resolve()
                return
            }
            var returnObjs = {}
            result.forEach(item => {
                var amount = Math.round(parseFloat(item.pubSharePreFee) * config.returnRate * 100) / 100
                var title = item.itemTitle.replace(/\+/g, '').replace(/&/g, '').replace(/%/g, '')
                if (returnObjs[item.customer_phone]) {
                    if (returnObjs[item.customer_phone].amount < 1 && returnObjs[item.customer_phone].amount + amount <= 200) {
                        returnObjs[item.customer_phone].amount += amount
                        returnObjs[item.customer_phone].remark += ';' + title
                        returnObjs[item.customer_phone].items.push(item)
                    }
                } else {
                    returnObjs[item.customer_phone] = {
                        customer_phone: item.customer_phone,
                        amount: amount,
                        remark: title,
                        items: [item]
                    }
                }
            })
            let promises = []
            for (var key in returnObjs) {
                if (returnObjs[key].amount >= 1) {
                    if (returnObjs[key].amount > 200) {
                        returnObjs[key].amount = 200
                    }
                    promises.push(doReturn(returnObjs[key]))
                }
            }
            Promise.all(promises).then(result => {
                resolve()
            })
        })
    })
}

function handleAllJdBills() {
    return new Promise(resolve => {
        mongoMng.db.collection('bill').find({
            orderId: {
                $ne: null
            },
            $or: [{
                finishDate: {
                    $nin: ['', '--']
                }
            }, {
                finishTime: {
                    $ne: 0
                },
            }],
            returnTime: null,
            customer_phone: {
                $ne: null
            }
        }).toArray((err, result) => {
            if (err) {
                logger.error('[' + __filename + ':' + __line + ']', err)
                resolve()
                return
            }
            var returnObjs = {}
            result.forEach(item => {
                if (!returnObjs[item.customer_phone]) {
                    returnObjs[item.customer_phone] = {
                        customer_phone: item.customer_phone,
                        amount: 0,
                        remark: '',
                        items: []
                    }
                }
                if (returnObjs[item.customer_phone].amount < 1) {
                    item.skus && item.skus.forEach(_item => {
                        returnObjs[item.customer_phone].remark += _item.skuName.replace(/\+/g, '').replace(/&/g, '').replace(/%/g, '') + ';'
                        returnObjs[item.customer_phone].amount += Math.round(_item.commission * config.returnRate * 100) / 100
                    })
                    item.skuList && item.skuList.forEach(_item => {
                        returnObjs[item.customer_phone].remark += _item.skuName.replace(/\+/g, '').replace(/&/g, '').replace(/%/g, '') + ';'
                        returnObjs[item.customer_phone].amount += Math.round(_item.actualFee * config.returnRate * 100) / 100
                    })
                    returnObjs[item.customer_phone].items.push(item)
                }
            })
            let promises = []
            for (var key in returnObjs) {
                if (returnObjs[key].amount >= 1) {
                    promises.push(doReturn(returnObjs[key]))
                }
            }
            Promise.all(promises).then(result => {
                resolve()
            })
        })
    })
}

function handleAllPromoters() {
    return new Promise(resolve => {
        mongoMng.db.collection('user').find({
            isPromoter: true
        }).toArray((err, result) => {
            if (err) {
                logger.error('[' + __filename + ':' + __line + ']', err)
                resolve()
                return
            }

            let promises = []
            result.forEach(item => {
                let promise = new Promise(resolve => {
                    let promoter_phone = item.phone
                    mongoMng.db.collection('user').find({
                        promoter: promoter_phone
                    }).toArray((err, result) => {
                        if (err) {
                            logger.error('[' + __filename + ':' + __line + ']', err)
                            resolve()
                            return
                        }

                        let customer_phones = []
                        result.forEach(item => {
                            customer_phones.push(item.phone)
                        })

                        mongoMng.db.collection('bill').find({
                            returnPromoterTime: null,
                            returnTime: {
                                $ne: null
                            },
                            customer_phone: {
                                $in: customer_phones
                            }
                        }).toArray((err, result) => {
                            if (err) {
                                logger.error('[' + __filename + ':' + __line + ']', err)
                                resolve()
                                return
                            }
                            let returnObj = {
                                customer_phone: promoter_phone,
                                amount: 0,
                                remark: '0单分享佣金',
                                items: []
                            }
                            result.forEach(item => {
                                returnObj.amount += item.returnMoney / config.returnRate * config.returnPromoterRate
                                returnObj.remark = returnObj.items.length + '单分享佣金'
                                returnObj.items.push(item)
                            })
                            returnObj.amount = Math.round(returnObj.amount * 100) / 100
                            if (returnObj.amount < 10) {
                                resolve()
                                return
                            }
                            doReturn(returnObj, 'promoter').then(result => {
                                resolve()
                            })
                        })
                    })
                })
            })
            if (promises.length = 0) {
                resolve()
                return
            }
            Promise.all(promises).then(result => {
                resolve()
            })
        })
    })
}

function handleRedPack20181212() {
    redPackNum = 200
    return new Promise(resolve => {
        mongoMng.db.collection('user').countDocuments({
            redPack20181212: {
                $ne: null
            }
        }, (err, sendCnt) => {
            if (err) {
                logger.error('[' + __filename + ':' + __line + ']', err)
                resolve()
                return
            }
            if (sendCnt >= redPackNum) {
                logger.error('[' + __filename + ':' + __line + ']', redPackNum + '个红包发完了')
                resolve()
                return
            }
            mongoMng.db.collection('user').find({
                redPack20181212: null,
                wechat: {
                    $ne: null
                }
            }).toArray((err, result) => {
                if (err) {
                    logger.error('[' + __filename + ':' + __line + ']', err)
                    resolve()
                    return
                }
                var phones = []
                var wechats = {}
                result.forEach(item => {
                    phones.push(item.phone)
                    wechats[item.phone] = item.wechat
                })
                mongoMng.db.collection('bill').aggregate([{
                    $match: {
                        customer_phone: {
                            $in: phones
                        },
                        createTime: {
                            $gt: '2018-12-12'
                        }
                    }
                }, {
                    $group: {
                        _id: '$customer_phone',
                        firstBillTime: {
                            $min: '$createTime'
                        }
                    }
                }, {
                    $sort: {
                        firstBillTime: 1
                    }
                }]).toArray((err, result) => {
                    if (err) {
                        logger.error('[' + __filename + ':' + __line + ']', err)
                        resolve()
                        return
                    }
                    let promises = []
                    for (var i = 0; i + sendCnt < redPackNum && i < result.length; i++) {
                        let total_amount = Math.round(getNormalDistribution(Math.random() * 2 - 1, 0, 1) * 2 * 1.8 * 100)
                        if (total_amount < 100)
                            total_amount = 100
                        if (total_amount > 260)
                            total_amount = 260

                        var mch_billno = getWechatBillno()
                        var remark = '新人红包'
                        var parm = {
                            act_name: '新人红包',
                            client_ip: '123.56.115.107',
                            mch_billno,
                            mch_id: '1510410651',
                            nonce_str: require('../util/randomString')(32),
                            re_openid: wechats[result[i]._id],
                            remark,
                            send_name: '旅悠省钱购',
                            total_amount,
                            total_num: 1,
                            wishing: '新人红包',
                            wxappid: 'wx226c3c9557c44304',
                        }

                        let phone = result[i]._id
                        let promise = new Promise(resolve => {
                            sendWechatRedPack(parm).then(result => {
                                mongoMng.db.collection('user').updateOne({
                                    phone,
                                    redPack20181212: null
                                }, {
                                    $set: {
                                        redPack20181212: {
                                            money: total_amount / 100,
                                            sendTime: new Date().getTime()
                                        }
                                    }
                                }, (err, result) => {
                                    if (err) {
                                        logger.error('[' + __filename + ':' + __line + ']', err)
                                        resolve()
                                        return
                                    }
                                    resolve()
                                })
                            }, result => {
                                if (result) {
                                    logger.error('[' + __filename + ':' + __line + ']', result)
                                }
                                resolve()
                            })
                        })
                        promises.push(promise)
                    }
                    Promise.all(promises).then(result => {
                        resolve()
                    })
                })
            })
        })
    })
}

exports.start = () => {
    return new Promise(resolve => {
        if (!mongoMng.db) {
            resolve()
            return
        }

        if (is_running) {
            resolve()
            return
        }
        is_running = true

        var p0 = findCustomerForAllBills()
        var p1 = handleAllTaobaoBills()
        var p2 = handleAllJdBills()
        var p3 = handleAllPromoters()
        var p4 = handleRedPack20181212()
        var p5 = handleAllTaobaoBills2()
        Promise.all([p0, p1, p2, p3, p4, p5]).then(result => {
            is_running = false
            resolve()
        })
    })
}

function doReturn(returnObj, type) {
    return new Promise(resolve => {
        type = type || 'customer'
        var customer_phone = returnObj.customer_phone
        returnObj.amount = Math.round(returnObj.amount * 100) / 100
        if (returnObj.amount < 1) {
            resolve()
            return
        }
        logger.debug('[' + __filename + ':' + __line + ']', customer_phone, returnObj.amount)
        mongoMng.db.collection('user').find({
            phone: customer_phone
        }).toArray((err, result) => {
            if (err) {
                logger.error('[' + __filename + ':' + __line + ']', err)
                resolve()
                return
            }
            if (result.length == 0) {
                logger.error('[' + __filename + ':' + __line + ']', '找不到用户[' + customer_phone + ']')
                resolve()
                return
            }
            var user = result[0]

            new Promise((resolve, reject) => {
                var returnWay = user.returnWay
                if (!returnWay) {
                    if (user.wechat)
                        returnWay = 'wechat'
                    else if (user.alipay)
                        returnWay = 'alipay'
                }
                if (returnWay == 'wechat' && user.wechat) {
                    var mch_billno = getWechatBillno()

                    var remark = returnObj.remark
                    while (Buffer.byteLength(remark, 'utf8') > 256) {
                        remark = remark.substring(0, remark.length - 1)
                    }

                    var parm = {
                        act_name: '省钱购',
                        client_ip: '123.56.115.107',
                        mch_billno,
                        mch_id: '1510410651',
                        nonce_str: randomString(32),
                        re_openid: user.wechat,
                        remark,
                        send_name: '旅悠省钱购',
                        total_amount: Math.round(returnObj.amount * 100),
                        total_num: 1,
                        wishing: '返还优惠',
                        wxappid: 'wx226c3c9557c44304',
                    }
                    if (type == 'promoter') {
                        parm.act_name = '推广'
                        parm.wishing = '推荐佣金'
                    }

                    sendWechatRedPack(parm).then(result => {
                        resolve()
                    }, result => {
                        if (result)
                            logger.error('[' + __filename + ':' + __line + ']', result)
                        reject(result)
                    })
                } else if (returnWay == 'alipay' && user.alipay) {
                    var remark = returnObj.remark
                    while (Buffer.byteLength(remark, 'utf8') > 200) {
                        remark = remark.substring(0, remark.length - 1)
                    }
                    var queryObj = {
                            app_id: '2016060201470909',
                            biz_content: JSON.stringify({
                                out_biz_no: require('../mng/alipayMng').out_biz_no,
                                payee_type: 'ALIPAY_LOGONID',
                                payee_account: user.alipay,
                                amount: returnObj.amount,
                                payer_show_name: '旅悠',
                                payee_real_name: '',
                                remark: remark
                            }),
                            charset: 'UTF8',
                            format: 'json',
                            method: 'alipay.fund.trans.toaccount.transfer',
                            sign_type: 'RSA2',
                            timestamp: formatDate(new Date()),
                            version: '1.0'
                        }
                        //logger.debug('[' + __filename + ':' + __line + ']', queryObj)

                    var queryString = ''
                    for (var key in queryObj)
                        queryString += key + '=' + queryObj[key] + '&'
                    queryString = queryString.substring(0, queryString.length - 1)
                    var sign = crypto.createSign('RSA-SHA256')
                    sign.update(queryString)
                    var result = sign.sign(`-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDRHshAcczm+JGr5aUasjj5Mbz9n4KbwlynKIK3sC8TO17YIkgIc74Xydyk0QIUyFf7SYqMslnA1e4BOXqTysdXlf+0Sc7iatDH1+suc4Ixmu4eMveigNB2VojC2+S5sMeCvM6P60vWwNOruQwe27z5hpcVzWCZnaMZUDZOb46PtD6fANrZ8nqCjqVofYcNRtSZ9IqCib7Q4lOpLpm91OxI6MHXsJWe3g+m3dhf0SQOJokF+f8SsAA54EeB1pcNvTkPVTarIYGTE8QJ3bbi2Xdj+1rN2YVy8cRVM7mc1s8Oa/Q/RRtwuWVQlyRxVuZcd/oGYDnnShmqJlLrHQ2QkaUvAgMBAAECggEAFkaGJD87CVtvAPWMWcSkRv8iV43XNspEXlX1XqW4zf6kArfcHnJdzGDnTPMqmpYgsRbLWGNjJiRjnuPFh9qw00aaH1VBYWLpbHA2kBMjyi7rsHHTaQ75pbFgDgmoWpNXHTkJc9Enme+eXItwnBTiE15f16Wx5YsiJX8i2cYOVIY4JygFacLDup7rgXwqJB7fAzHJRpQO9Mey99sW3yjSijAMTDhik73WGI9K10CUWjPUsHUxF0JrSh7jKGoUhxS0rfpB0tat2cYZXlCX6CvCfSXlHk4u4fHZAqz/6VQVAekf7+1mGLv/dsAVklHZ4quiUdrEYSYppHcQj3RP2fWBqQKBgQD+EGyqHqtotDcNfuQrl8XPo8hVMjOzCvHdisndA/3TjSqVpE3dmoT6hEr00zCvlpl+H/RisvzBRO9SAqcru/z+oxHtHMCtiFqtoTivyW+Y5410YK6mfB/Snohg97zEKMU24YRBfSGB5GvIu4iGqevH6/tI/GIhRqAN24aQWFnVIwKBgQDStrDF1/wF1lAI2B58j/rfQu6xnXFiB3ujDpYR1ILf2zi+8rWtDDeSPeqEjTK2l73IQb2IQvfWUJNT6doysYbiNETC7vzf6BuB1upmrCV0G2JEAN33DWHz5QVjfMzyqGftjMozm27PQ0LaPzJeNiQDjLsuv3fDx5LY02pc3aoOhQKBgFDf7Zdh1/Kmm3fCUuPFloR4gIcOSgLOkxuQ2J1wbdZv84RbHyZRz87nWe0BZVgfupC5n1Pj4i2rwfr7OTfkya5NPqGaK4OSCjuHPMJIfyvPWeoX9MCudnrXWFZ1xjMzP0QvGai3KnlsuxrVB6rGYHXtmrorDRnGn6CJpxY/6ai9AoGARpHzAD/G4zmUknG3PCaIcc+b25aMS7WP3dtbvVr7/fcQuTrWR7+IuQzNh1k2u9p0MCZ8UK+FC5zuyrLOZh34u7efs92QiXjWBZUx6fMLlCg7r+TOchhkTufL9zbr+PUX4YI+kiwjX3z6Xde+ibj+NMYkRpLPjJ1BfCbKP5Hpi3UCgYEAkjRK7f48KkAyU6PgAltb1CZ/1FafDgAjGjQv9+xxJwqncnAUBTMl/EWSHyCZ7V8a3JB3T8b9ToQniH8l8S/Xcup5e1uRYsCNUaD+5pEA+87Dta+GZEOYmFJ/bOTIYsRMUXbjfAwwu0qRafnesXw/2lIag4n0UkhC9YwT3N2p4Hc=
-----END PRIVATE KEY-----`, 'base64')

                    var verify = crypto.createVerify('RSA-SHA256')
                    verify.update(queryString)
                        //        logger.debug('[' + __filename + ':' + __line + ']', verify.verify(`-----BEGIN PUBLIC KEY-----
                        //MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0R7IQHHM5viRq+WlGrI4+TG8/Z+Cm8JcpyiCt7AvEzte2CJICHO+F8ncpNECFMhX+0mKjLJZwNXuATl6k8rHV5X/tEnO4mrQx9frLnOCMZruHjL3ooDQdlaIwtvkubDHgrzOj+tL1sDTq7kMHtu8+YaXFc1gmZ2jGVA2Tm+Oj7Q+nwDa2fJ6go6laH2HDUbUmfSKgom+0OJTqS6ZvdTsSOjB17CVnt4Ppt3YX9EkDiaJBfn/ErAAOeBHgdaXDb05D1U2qyGBkxPECd224tl3Y/tazdmFcvHEVTO5nNbPDmv0P0UbcLllUJckcVbmXHf6BmA550oZqiZS6x0NkJGlLwIDAQAB
                        //-----END PUBLIC KEY-----`, result, 'base64'))

                    queryObj.sign = result
                    var biz_content = queryObj.biz_content
                    delete queryObj.biz_content
                    var timestamp = queryObj.timestamp.replace(/ /g, '+').replace(/:/g, '%3A')
                    delete queryObj.timestamp
                    var url = 'https://openapi.alipay.com/gateway.do?' + require('querystring').stringify(queryObj) + '&timestamp=' + timestamp

                    require('../util/getHtml')({
                        url: url,
                        data: 'biz_content=' + biz_content
                    }).then(result => {
                        var obj = JSON.parse(result)
                        logger.debug('[' + __filename + ':' + __line + ']', biz_content, result)
                        if (obj.alipay_fund_trans_toaccount_transfer_response.code != '10000' || obj.alipay_fund_trans_toaccount_transfer_response.msg != 'Success') {
                            let content = obj.alipay_fund_trans_toaccount_transfer_response.sub_msg != '付款方余额不足' ? obj.alipay_fund_trans_toaccount_transfer_response.sub_msg : ('账户余额不足，给' + customer_phone + '需要' + returnObj.amount)
                            require('../mng/pushMng').push(content)
                            reject()
                            return
                        }
                        resolve()
                    }, result => {
                        logger.error('[' + __filename + ':' + __line + ']', result)
                        reject()
                    })
                } else {
                    logger.error('[' + __filename + ':' + __line + ']', '用户[' + customer_phone + ']没有绑定微信和支付宝')
                    reject()
                }
            }).then(result => {
                let promises = []
                returnObj.items.forEach(item => {
                    let promise = new Promise(resolve => {
                        let set = {}
                        if (type == 'customer') {
                            let money = 0
                            if (item.taobaoTradeParentId) {
                                money = Math.round(parseFloat(item.feeString) * config.returnRate * 100) / 100
                            } else if (item.orderId) {
                                item.skus && item.skus.forEach(_item => {
                                    money += _item.commission * config.returnRate
                                })
                                item.skuList && item.skuList.forEach(_item => {
                                    money += _item.actualFee * config.returnRate
                                })
                                money = Math.round(money * 100) / 100
                            } else if (item.tradeParentId) {
                                money = Math.round(parseFloat(item.pubSharePreFee) * config.returnRate * 100) / 100
                            }
                            set = {
                                returnTime: formatDate(new Date()),
                                returnMoney: money
                            }
                        } else if (type == 'promoter') {
                            let money = 0
                            if (item.taobaoTradeParentId) {
                                money = Math.round(parseFloat(item.feeString) * config.returnPromoterRate * 100) / 100
                            } else if (item.orderId) {
                                item.skuList.forEach(_item => {
                                    money += _item.actualFee * config.returnPromoterRate
                                })
                                money = Math.round(money * 100) / 100
                            } else if (item.tradeParentId) {
                                money = Math.round(parseFloat(item.pubSharePreFee) * config.returnPromoterRate * 100) / 100
                            }
                            set = {
                                returnPromoterTime: formatDate(new Date()),
                                returnPromoterMoney: money
                            }
                        }
                        mongoMng.db.collection('bill').updateOne({
                                _id: item._id
                            }, {
                                $set: set,
                                // $unset: {
                                //   advLink: ''
                                // }
                            },
                            // {
                            //   multi: true
                            // },
                            (err, result) => {
                                if (err) {
                                    logger.error('[' + __filename + ':' + __line + ']', err)
                                    resolve()
                                    return
                                }
                                //logger('[' + __filename + ':' + __line + ']', '更新成功', item)
                                resolve()
                            })
                    })
                    promises.push(promise)
                    Promise.all(promises).then(result => {
                        resolve()
                    })
                })
            }, result => {
                result && logger.error('[' + __filename + ':' + __line + ']', result)
                resolve()
            })
        })
    })
}

exports.findCustomerForBill = item => {
    return new Promise((resolve, reject) => {
        if (item.taobaoTradeParentId) { // 淘宝订单
            new Promise((resolve, reject) => {
                // 按taobaoTradeParentId匹配
                matchTaobaoBillWithTaobaoTradeParentId(item).then(result => {
                    resolve(result)
                }, result => {
                    var customer_phone_list = result
                    matchTaobaoBillWithLog(item).then(result => {
                        resolve(result)
                    }, result => {
                        result.forEach(phone => {
                            if (customer_phone_list.indexOf(phone) == -1) {
                                customer_phone_list.push(phone)
                            }
                        })
                        matchTaobaoBillWithExShopTitle(item).then(result => {
                            resolve(result)
                        }, result => {
                            result.forEach(phone => {
                                if (customer_phone_list.indexOf(phone) == -1) {
                                    customer_phone_list.push(phone)
                                }
                            })
                            matchTaobaoBillWithLast6TaobaoTradeParentId(item).then(result => {
                                resolve(result)
                            }, result => {
                                result.forEach(phone => {
                                    if (customer_phone_list.indexOf(phone) == -1) {
                                        customer_phone_list.push(phone)
                                    }
                                })
                                reject(customer_phone_list)
                            })
                        })
                    })
                })
            }).then(result => {
                mongoMng.db.collection('bill').updateMany({
                    taobaoTradeParentId: item.taobaoTradeParentId,
                    customer_phone: null
                }, {
                    $set: {
                        customer_phone: result
                    }
                }, {
                    multi: true
                }, (err) => {
                    if (err) {
                        logger.error('[' + __filename + ':' + __line + ']', err)
                        reject()
                        return
                    }
                    resolve(result)
                })
            }, result => {
                reject(result)
            })
        } else if (item.orderId) { //京东订单
            // 用parentId匹配
            new Promise((resolve, reject) => {
                if (item.parentId == 0) {
                    reject()
                    return
                }
                mongoMng.db.collection('bill').find({
                    orderId: {
                        $ne: null
                    },
                    parentId: item.parentId,
                    customer_phone: {
                        $ne: null
                    }
                }).toArray((err, result) => {
                    if (err) {
                        logger.error('[' + __filename + ':' + __line + ']', err)
                        reject()
                        return
                    }
                    var customer_phone_list = []
                    result.forEach(item => {
                        if (customer_phone_list.indexOf(item.customer_phone) == -1) {
                            customer_phone_list.push(item.customer_phone)
                        }
                    })
                    if (customer_phone_list.length == 1) {
                        mongoMng.db.collection('bill').updateOne({
                            orderId: item.orderId
                        }, {
                            $set: {
                                customer_phone: customer_phone_list[0]
                            }
                        }, (err, result) => {
                            if (err) {
                                logger.error('[' + __filename + ':' + __line + ']', err)
                                reject()
                                return
                            }
                            resolve(customer_phone_list[0])
                        })
                    } else {
                        reject()
                    }
                })
            }).then(result => {
                resolve(result)
            }, result => {
                // 根据日志匹配
                var promises = []
                if (!item.skuList) {
                    logger.error('[' + __filename + ':' + __line + ']', '匹配不出', JSON.stringify(item))
                    reject()
                    return
                }
                var minDate = new Date()
                minDate.setTime(minDate.getTime() - 90 * 86400 * 1000)
                item.skuList.forEach(item => {
                    promises.push(new Promise((resolve, reject) => {
                        mongoMng.db.collection('log').find({
                            $or: [{
                                link: new RegExp('^https?://item.jd.com/' + item.skuId + '.html')
                            }, {
                                link: new RegExp('^https?://item.m.jd.com/product/' + item.skuId + '.html')
                            }],
                            customer_phone: {
                                $ne: null
                            },
                            time: {
                                $gte: formatDate(minDate),
                                // $lte: formatDate(maxDate)
                            }
                        }).toArray((err, result) => {
                            if (err) {
                                logger.error('[' + __filename + ':' + __line + ']', err)
                                reject()
                                return
                            }
                            var customer_phone_list = []
                            result.forEach(item => {
                                if (customer_phone_list.indexOf(item.customer_phone) == -1) {
                                    customer_phone_list.push(item.customer_phone)
                                }
                            })
                            resolve(customer_phone_list)
                        })
                    }))
                })
                Promise.all(promises).then(result => {
                    var j = 0
                    for (; j < result.length; ++j) {
                        if (result[j].length > 0) {
                            break
                        }
                    }
                    var customer_phone_list = []
                    if (j < result.length) {
                        result[j].forEach(item => {
                            for (var i = j + 1; i < result.length; ++i) {
                                if (result[i].length != 0 && result[i].indexOf(item) == -1) {
                                    return
                                }
                            }
                            customer_phone_list.push(item)
                        })
                    }
                    if (customer_phone_list.length == 1) {
                        mongoMng.db.collection('bill').updateOne({
                            orderId: item.orderId
                        }, {
                            $set: {
                                customer_phone: customer_phone_list[0]
                            }
                        }, (err, result) => {
                            if (err) {
                                logger.error('[' + __filename + ':' + __line + ']', err)
                                reject()
                                return
                            }
                            resolve(customer_phone_list)
                        })
                    } else {
                        reject(customer_phone_list)
                    }
                }, result => {
                    if (result)
                        logger.error('[' + __filename + ':' + __line + ']', result)
                    reject()
                })
            })
        } else if (item.tradeParentId) { // 新淘宝订单
            new Promise((resolve, reject) => {
                matchTaobaoBillWithTradeParentId(item).then(result => {
                    resolve(result)
                }, result => {
                    var customer_phone_list = result
                    matchTaobaoBillWithLog2(item).then(result => {
                        resolve(result)
                    }, result => {
                        result.forEach(phone => {
                            if (customer_phone_list.indexOf(phone) == -1) {
                                customer_phone_list.push(phone)
                            }
                        })
                        matchTaobaoBillWithShopName(item).then(result => {
                            resolve(result)
                        }, result => {
                            result.forEach(phone => {
                                if (customer_phone_list.indexOf(phone) == -1) {
                                    customer_phone_list.push(phone)
                                }
                            })
                            matchTaobaoBillWithLast6TradeParentId(item).then(result => {
                                resolve(result)
                            }, result => {
                                result.forEach(phone => {
                                    if (customer_phone_list.indexOf(phone) == -1) {
                                        customer_phone_list.push(phone)
                                    }
                                })
                                reject(customer_phone_list)
                            })
                        })
                    })
                })
            }).then(result => {
                mongoMng.db.collection('bill').updateMany({
                    tradeParentId: item.tradeParentId,
                    customer_phone: null
                }, {
                    $set: {
                        customer_phone: result
                    }
                }, {
                    multi: true
                }, (err) => {
                    if (err) {
                        logger.error('[' + __filename + ':' + __line + ']', err)
                        reject()
                        return
                    }
                    resolve(result)
                })
            }, result => {
                reject(result)
            })
        } else {
            logger.error('[' + __filename + ':' + __line + ']', '有奇怪订单', item)
        }
    })
}

function matchTaobaoBillWithTaobaoTradeParentId(item) {
    return new Promise((resolve, reject) => {
        if (!item.taobaoTradeParentId) {
            reject([])
            return
        }
        mongoMng.db.collection('bill').find({
            taobaoTradeParentId: item.taobaoTradeParentId,
            customer_phone: {
                $ne: null
            }
        }).toArray((err, result) => {
            if (err) {
                logger.error('[' + __filename + ':' + __line + ']', err)
                reject([])
                return
            }
            var customer_phone_list = []
            result.forEach(item => {
                if (customer_phone_list.indexOf(item.customer_phone) == -1) {
                    customer_phone_list.push(item.customer_phone)
                }
            })
            if (customer_phone_list.length == 1) {
                resolve(customer_phone_list[0])
            } else {
                reject(customer_phone_list)
            }
        })
    })
}

function matchTaobaoBillWithLog(item) {
    return new Promise((resolve, reject) => {
        if (!item.auctionId) {
            reject([])
            return
        }
        var minDate = new Date()
        minDate.setTime(minDate.getTime() - 90 * 86400 * 1000)
            // var maxDate = new Date(item.createTime)
            // maxDate.setTime(maxDate.getTime() + 101000)
        mongoMng.db.collection('log').find({
            $or: [{
                link: new RegExp('id=' + item.auctionId),
            }, {
                link: new RegExp('http://a.m.tmall.com/i' + item.auctionId + '.htm'),
            }, {
                link: new RegExp('https://a.m.taobao.com/i' + item.auctionId + '.htm'),
            }],
            customer_phone: {
                $ne: null
            },
            time: {
                $gte: formatDate(minDate),
                // $lte: formatDate(maxDate)
            }
        }).toArray((err, result) => {
            if (err) {
                logger.error('[' + __filename + ':' + __line + ']', err)
                reject()
                return
            }
            var customer_phone_list = []
            result.forEach(_item => {
                if (customer_phone_list.indexOf(_item.customer_phone) == -1) {
                    customer_phone_list.push(_item.customer_phone)
                }
            })
            if (customer_phone_list.length == 1) {
                resolve(customer_phone_list[0])
            } else {
                reject(customer_phone_list)
            }
        })
    })
}

function matchTaobaoBillWithExShopTitle(item) {
    return new Promise((resolve, reject) => {
        if (!item.exShopTitle) {
            reject([])
            return
        }
        mongoMng.db.collection('bill').find({
            exShopTitle: item.exShopTitle,
            customer_phone: {
                $ne: null
            }
        }).toArray((err, result) => {
            if (err) {
                logger.error('[' + __filename + ':' + __line + ']', err)
                reject([])
                return
            }
            var customer_phone_list = []
            result.forEach(item => {
                if (customer_phone_list.indexOf(item.customer_phone) == -1) {
                    customer_phone_list.push(item.customer_phone)
                }
            })
            if (customer_phone_list.length == 1) {
                resolve(customer_phone_list[0])
            } else {
                reject(customer_phone_list)
            }
        })
    })
}

function matchTaobaoBillWithLast6TaobaoTradeParentId(item) {
    return new Promise((resolve, reject) => {
        if (!item.taobaoTradeParentId) {
            reject([])
            return
        }
        mongoMng.db.collection('bill').find({
            taobaoTradeParentId: new RegExp(item.taobaoTradeParentId.substring(item.taobaoTradeParentId.length - 6) + '$'),
            customer_phone: {
                $ne: null
            }
        }, {
            projection: {
                customer_phone: 1
            }
        }).toArray((err, result) => {
            if (err) {
                logger.error('[' + __filename + ':' + __line + ']', err)
                reject([])
                return
            }
            var customer_phone_list = []
            result.forEach(item => {
                if (customer_phone_list.indexOf(item.customer_phone) == -1) {
                    customer_phone_list.push(item.customer_phone)
                }
            })
            if (customer_phone_list.length == 1) {
                resolve(customer_phone_list[0])
            } else {
                reject(customer_phone_list)
            }
        })
    })
}

function matchTaobaoBillWithTradeParentId(item) {
    return new Promise((resolve, reject) => {
        if (!item.tradeParentId) {
            reject([])
            return
        }
        mongoMng.db.collection('bill').find({
            tradeParentId: item.tradeParentId,
            customer_phone: {
                $ne: null
            }
        }).toArray((err, result) => {
            if (err) {
                logger.error('[' + __filename + ':' + __line + ']', err)
                reject([])
                return
            }
            var customer_phone_list = []
            result.forEach(item => {
                if (customer_phone_list.indexOf(item.customer_phone) == -1) {
                    customer_phone_list.push(item.customer_phone)
                }
            })
            if (customer_phone_list.length == 1) {
                resolve(customer_phone_list[0])
            } else {
                reject(customer_phone_list)
            }
        })
    })
}

function matchTaobaoBillWithLog2(item) {
    return new Promise((resolve, reject) => {
        if (!item.itemId) {
            reject([])
            return
        }
        var minDate = new Date()
        minDate.setTime(minDate.getTime() - 90 * 86400 * 1000)
            // var maxDate = new Date(item.createTime)
            // maxDate.setTime(maxDate.getTime() + 101000)
        mongoMng.db.collection('log').find({
            $or: [{
                link: new RegExp('id=' + item.itemId),
            }, {
                link: new RegExp('http://a.m.tmall.com/i' + item.itemId + '.htm'),
            }, {
                link: new RegExp('https://a.m.taobao.com/i' + item.itemId + '.htm'),
            }],
            customer_phone: {
                $ne: null
            },
            time: {
                $gte: formatDate(minDate),
                // $lte: formatDate(maxDate)
            }
        }).toArray((err, result) => {
            if (err) {
                logger.error('[' + __filename + ':' + __line + ']', err)
                reject()
                return
            }
            var customer_phone_list = []
            result.forEach(_item => {
                if (customer_phone_list.indexOf(_item.customer_phone) == -1) {
                    customer_phone_list.push(_item.customer_phone)
                }
            })
            if (customer_phone_list.length == 1) {
                resolve(customer_phone_list[0])
            } else {
                reject(customer_phone_list)
            }
        })
    })
}

function matchTaobaoBillWithShopName(item) {
    return new Promise((resolve, reject) => {
        if (!item.shopName) {
            reject([])
            return
        }
        mongoMng.db.collection('bill').find({
            shopName: item.shopName,
            customer_phone: {
                $ne: null
            }
        }).toArray((err, result) => {
            if (err) {
                logger.error('[' + __filename + ':' + __line + ']', err)
                reject([])
                return
            }
            var customer_phone_list = []
            result.forEach(item => {
                if (customer_phone_list.indexOf(item.customer_phone) == -1) {
                    customer_phone_list.push(item.customer_phone)
                }
            })
            if (customer_phone_list.length == 1) {
                resolve(customer_phone_list[0])
            } else {
                reject(customer_phone_list)
            }
        })
    })
}

function matchTaobaoBillWithLast6TradeParentId(item) {
    return new Promise((resolve, reject) => {
        if (!item.tradeParentId) {
            reject([])
            return
        }
        mongoMng.db.collection('bill').find({
            tradeParentId: new RegExp(item.tradeParentId.substring(item.tradeParentId.length - 6) + '$'),
            customer_phone: {
                $ne: null
            }
        }, {
            projection: {
                customer_phone: 1
            }
        }).toArray((err, result) => {
            if (err) {
                logger.error('[' + __filename + ':' + __line + ']', err)
                reject([])
                return
            }
            var customer_phone_list = []
            result.forEach(item => {
                if (customer_phone_list.indexOf(item.customer_phone) == -1) {
                    customer_phone_list.push(item.customer_phone)
                }
            })
            if (customer_phone_list.length == 1) {
                resolve(customer_phone_list[0])
            } else {
                reject(customer_phone_list)
            }
        })
    })
}

exports.sendWechatRedPack = sendWechatRedPack
exports.getWechatBillno = getWechatBillno